/**
 *
 */
package com.nest.WorkNest.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.adapter.LargeOrderAdapter;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.view.ListViewForScrollView;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.stevenhu.android.phone.bean.ADInfo;
import com.stevenhu.android.phone.utils.ViewFactory;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.androiddevelop.cycleviewpager.lib.CycleViewPager;

/**
 *
 *
 * @version
 *
 */
public class BulkOrderDetailAct extends BaseActivity implements OnClickListener {
    @Bind(R.id.bulkorder_status)
    TextView productStatus;
    @Bind(R.id.bulkorder_total)
    TextView productTotal;
    @Bind(R.id.bulkorder_perPrice)
    TextView productPerPrice;
    @Bind(R.id.bulkorder_totalprice)
    TextView productTotalprice;
    @Bind(R.id.bulkorder_requiredExplain)
    TextView productRequiredExplain;
    @Bind(R.id.bulkorder_userReceiveAddress)
    TextView productUserReceiveAddress;
    @Bind(R.id.bulkorder_deliveryTime)
    TextView productDeliveryTime;
    @Bind(R.id.product_deliveryWay)
    TextView productDeliveryWay;
    @Bind(R.id.bulkorder_productname)
    TextView productProductname;
    @Bind(R.id.bulkorder_productId)
    TextView productProductId;
    @Bind(R.id.imgBtn_bulkorder_call)
    ImageButton imgBtnBulkorderCall;
    @Bind(R.id.bulkorder_bulkId)
    TextView bulkorderBulkId;
    @Bind(R.id.bulkorder_ordertime)
    TextView bulkorderOrdertime;
    private Context context = BulkOrderDetailAct.this;
    private ListViewForScrollView listview;
    private LargeOrderAdapter lAdapter;
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private ArrayList<HashMap<String, String>> imgList = new ArrayList<HashMap<String, String>>();
    private ArrayList<HashMap<String, String>> numList = new ArrayList<HashMap<String, String>>();
    private LayoutInflater lif;
    private ArrayList<HashMap<String, String>> addressinfo = new ArrayList<>();
    private TextView delivery_btn, status_btn;
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private String bulkOrderId, mainImage;
    private HashMap<String, String> data = new HashMap<>();
    private CycleViewPager cycleViewPager;
    private String[] imgUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_bulkorderdetail);
        ButterKnife.bind(this);
        initView();
        loadBulkorderDetail();
        configImageLoader();
    }

    private void initView() {
        initBar();
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("大货单详情");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        back();
        listview = (ListViewForScrollView) findViewById(R.id.act_listview);
        lAdapter = new LargeOrderAdapter(this, numList);
        lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headerView = lif.inflate(R.layout.header_bulkorderdetail, null);
        listview.addHeaderView(headerView);
        listview.setAdapter(lAdapter);
        // listview.setOverScrollMode(View.OVER_SCROLL_NEVER);// 去掉下拉底部出现的阴影
        delivery_btn = (TextView) findViewById(R.id.delivery_btn);
        status_btn = (TextView) findViewById(R.id.status_btn);
        delivery_btn.setOnClickListener(this);
        status_btn.setOnClickListener(this);
    }

    public void loadBulkorderDetail() {
        bulkOrderId = getIntent().getStringExtra("bulkOrderId");
        mainImage = getIntent().getStringExtra("mainImage");
        if ("1".equals(getIntent().getStringExtra("waitpay"))) {
            delivery_btn.setVisibility(View.INVISIBLE);
        }
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    String BulkOrder = Tool.getString(result, "bulkOrder");
                    data = Tool.getMapByJsonObj(BulkOrder);
                    productProductname.setText(data.get("productName"));
                    productProductId.setText(data.get("productId"));
                    productStatus.setText(data.get("statusNote"));
                    productTotal.setText(data.get("totalQuantity"));
                    productPerPrice.setText(data.get("perPrice"));
                    productTotalprice.setText(data.get("totalPrice"));
                    productRequiredExplain.setText(data.get("requiredExplain"));
                    productDeliveryTime.setText(data.get("deliveryTime"));
                    productDeliveryWay.setText(data.get("deliveryWay"));
                    bulkorderBulkId.setText(data.get("bulkOrderId"));
                    bulkorderOrdertime.setText(data.get("orderTime"));
//                    productUserReceiveAddress.setText(data.get("userReceiveAddress"));
                    loadAddressInfo(data.get("userReceiveAddress"));
                    JSONArray imgarray = Tool.getJsonArray(result, "imageList");
                    imgList.clear();
                    imgList = Tool.getListMapByJsonArray(imgarray);
                    imgUrl = new String[imgList.size()];
                    for (int i = 0; i < imgList.size(); i++) {
                        String image = imgList.get(i).get("url");
                        if (!image.substring(0, 1).equals("h")) {
                            image = "http://" + image;
                        }
                        imgUrl[i] = image;
                    }
                    JSONArray numArray = Tool.getJsonArray(result, "numList");
                    numList = Tool.getListMapByJsonArray(numArray);
                    lAdapter.update(numList);
                    if (imgList.size() != 0) {
                        initialize();
                    }
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostBulkorderDetail(context, bulkOrderId, ioAuthCallBack);
    }


    /*
     * (non-Javadoc)
     *
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        if (v == delivery_btn) {
            Intent DRintent = new Intent(this, DeliveryRecordAct.class);
            bulkOrderId = getIntent().getStringExtra("bulkOrderId");
            DRintent.putExtra("bulkOrderId", bulkOrderId);
            DRintent.putExtra("productId", data.get("productId"));
            DRintent.putExtra("productName", data.get("productName"));
            DRintent.putExtra("mainImage", mainImage);
            startActivity(DRintent);
        } else if (v == status_btn) {
            Intent SRintent = new Intent(this, StatusRecordAct.class);
            SRintent.putExtra("bulkOrderId", bulkOrderId);
            SRintent.putExtra("productId", data.get("productId"));
            SRintent.putExtra("productName", data.get("productName"));
            SRintent.putExtra("imgUrl", mainImage);
            startActivity(SRintent);
        }
    }

    @SuppressLint("NewApi")
    private void initialize() {

        cycleViewPager = (CycleViewPager) getFragmentManager()
                .findFragmentById(com.stevenhu.android.phone.ui.R.id.fragment_cycle_viewpager_content);

        for (int i = 0; i < imgUrl.length; i++) {
            ADInfo info = new ADInfo();
            info.setUrl(imgUrl[i]);
            info.setContent("图片-->" + i);
            infos.add(info);
        }

        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(this, infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(this, infos.get(i).getUrl()));
            views.get(i).setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(this, infos.get(0).getUrl()));
        for (int j = 0; j < views.size(); j++) {
            views.get(j).setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        }
        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(false);
        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(false);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
            }

        }

    };

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(com.stevenhu.android.phone.ui.R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(com.stevenhu.android.phone.ui.R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(com.stevenhu.android.phone.ui.R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                        // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }

    private void loadAddressInfo(final String addressId) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                JSONObject jsonObject = Tool.getJsonObject(result);
                JSONArray jsonArray;
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    jsonArray = Tool.getJsonArray(result, "dataList");

                    addressinfo = Tool.getListMapByJsonArray(jsonArray);
                    if (addressinfo.size() != 0) {
                        productUserReceiveAddress.setText(addressinfo.get(0).get("province") + "省"
                                + addressinfo.get(0).get("city") + addressinfo.get(0).get("address"));
                    } else {
                        productUserReceiveAddress.setText("无");
                    }
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostAddressList(context, addressId, ioAuthCallBack);
    }
}
